package com.have.blog.picture.service.impl;

import com.have.blog.admin.service.SystemConfigFeignApi;
import com.have.blog.base.constant.BaseBlogConstant;
import com.have.blog.base.constant.BaseConstant;
import com.have.blog.base.dto.SystemConfigDto;
import com.have.blog.base.enums.BlogOpenStatus;
import com.have.blog.base.enums.BlogStatus;
import com.have.blog.base.wrapper.Wrapper;
import com.have.blog.config.hloder.RequestHolder;
import com.have.blog.model.mapper.FileSourceMapper;
import com.have.blog.model.mapper.PictureMapper;
import com.have.blog.model.models.*;
import com.have.blog.picture.dto.PictureUrlDto;
import com.have.blog.picture.service.LocalFileService;
import com.have.blog.picture.service.MinioService;
import com.have.blog.picture.service.PictureService;
import com.have.blog.picture.service.QiniuService;
import com.have.blog.utils.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service
@SuppressWarnings("all")
@Slf4j
public class PictureServiceImpl implements PictureService {
    @Autowired
    private SystemConfigFeignApi systemConfigFeignApi;
    @Autowired
    private FileSourceMapper fileSourceMapper;
    @Autowired
    private PictureMapper pictureMapper;
    @Autowired
    private LocalFileService localFileService;
    @Autowired
    private QiniuService qiniuService;
    @Autowired
    private MinioService minioService;

    @Override
    public Wrapper<List<PictureUrlDto>> cropperPicture(ArrayList<MultipartFile> list) {
        Wrapper<SystemConfigDto> wrapperSystemConfig = systemConfigFeignApi.getSystemConfig();
        if (wrapperSystemConfig.isSuccess()) {
            Wrapper<List<Picture>> listWrapper = batchUploadPicture(list);
            if (listWrapper.isError()) {
                return Wrapper.failed(listWrapper.getMessage());
            }
            List<Picture> pictureList = listWrapper.getData();
            SystemConfigDto systemConfigDto = wrapperSystemConfig.getData();
            List<PictureUrlDto> resultList = new ArrayList<>();
            for (Picture picture : pictureList) {
                PictureUrlDto dto = new PictureUrlDto();
                dto.setUid(picture.getUid());
                Integer picturePriority = Integer.valueOf(systemConfigDto.getPicturePriority());
                if (picturePriority == 0) {
                    dto.setUrl(systemConfigDto.getLocalPictureBaseUrl() + picture.getLocalUrl());
                } else if (picturePriority == 1) {
                    dto.setUrl(systemConfigDto.getQiNiuPictureBaseUrl() + picture.getQiniuUrl());
                } else {
                    dto.setUrl(systemConfigDto.getMinioPictureBaseUrl() +  picture.getMinioUrl());

                }
                resultList.add(dto);
            }
            log.info("成功截取图片:{}", pictureList);
            return Wrapper.success(resultList);
        }
        return Wrapper.failed(wrapperSystemConfig.getMessage());

    }

    @Override
    public Wrapper<Map<Integer, String>> getPictures(List<Integer> pictureUids) {
        Wrapper<SystemConfigDto> wrapperSystemConfig = systemConfigFeignApi.getSystemConfig();
        if (wrapperSystemConfig.isError()) {
            log.error("系统配置错误:{}", wrapperSystemConfig.getMessage());
            return Wrapper.failed();
        }
        SystemConfigDto systemConfigDto = wrapperSystemConfig.getData();
        Integer picturePriority = Integer.valueOf(systemConfigDto.getPicturePriority());

        PictureExample example = new PictureExample();
        example.createCriteria()
                .andStatusEqualTo(BlogStatus.ENABLE.getStatus())
                .andUidIn(pictureUids);
        List<Picture> pictureList = pictureMapper.selectByExample(example);
        Map<Integer, String> resultMap = new HashMap<>();
        int i = 0;
        for (Picture picture : pictureList) {
            String url = "";
            if (picturePriority == 0) { // 本地上传
                url = systemConfigDto.getLocalPictureBaseUrl() + picture.getLocalUrl();
            } else if (picturePriority == 1) {
                url = systemConfigDto.getQiNiuPictureBaseUrl() + picture.getQiniuUrl();
            } else if (picturePriority == 2) {
                url = systemConfigDto.getMinioPictureBaseUrl() + picture.getMinioUrl();
            }
            resultMap.put(picture.getUid(), url);
        }
        return Wrapper.success(resultMap);
    }

    @Override
    public Wrapper<String> getPicture(Integer pictureUid) {
        Wrapper<SystemConfigDto> wrapperSystemConfig = systemConfigFeignApi.getSystemConfig();
        if (wrapperSystemConfig.isError()) {
            log.error("系统配置错误:{}", wrapperSystemConfig.getMessage());
            return Wrapper.failed();
        }
        SystemConfigDto systemConfigDto = wrapperSystemConfig.getData();
        Integer picturePriority = systemConfigDto.getPicturePriority() == null? 1 :Integer.valueOf(systemConfigDto.getPicturePriority());

        Picture picture = pictureMapper.selectByPrimaryKey(pictureUid);
        if (picture == null) {
            return Wrapper.failed("Picture not exist");
        }
        String url = "";
        if (picturePriority == 0) { // 本地上传
            url = systemConfigDto.getLocalPictureBaseUrl() + picture.getLocalUrl();
        } else if (picturePriority == 1) {
            url = systemConfigDto.getQiNiuPictureBaseUrl() + picture.getQiniuUrl();
        } else if (picturePriority == 2) {
            url = systemConfigDto.getMinioPictureBaseUrl() + picture.getMinioUrl();
        }
        return Wrapper.success(url);
    }

    // TODO  批量插入修改
    @Transactional
    @Override
    public Wrapper<List<Picture>> batchUploadPicture(List<MultipartFile> filedatas) {
        Wrapper<SystemConfigDto> wrapperSystemConfig = systemConfigFeignApi.getSystemConfig();
        if (wrapperSystemConfig.isError()) {
            log.error("系统配置错误:{}", wrapperSystemConfig.getMessage());
            return Wrapper.failed();
        }
        SystemConfigDto systemConfig = wrapperSystemConfig.getData();
        HttpServletRequest request = RequestHolder.getRequest();
        String uploadQiNiu = systemConfig.getUploadQiNiu();
        String uploadLocal = systemConfig.getUploadLocal();
        String uploadMinio = systemConfig.getUploadMinio();

        // 如果是用户上传，则需要上传用户uid
        Integer userUid;
        // 如果是管理员上传，则需要上传管理员uid
        Integer adminUid;
        // 项目名
        String projectName;
        // source name indicate file from where
        String sourceName;

        userUid = null; // if exist, file from web
        adminUid = 1; // if exist, file from admin
        projectName = "blog";
        sourceName = "admin";

        if (StringUtils.isEmpty(projectName)) {
            projectName = "base";
        }

        FileSourceExample example = new FileSourceExample();
        example.createCriteria()
                .andSourceNameEqualTo(sourceName)
                .andProjectNameEqualTo(projectName)
                .andStatusEqualTo(BlogStatus.ENABLE.getStatus());
        List<FileSource> fileSources = fileSourceMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(fileSources)) {
            return Wrapper.failed("文件不允许被上传");
        }

        // 如果url为空，使用默认url
        FileSource fileSource = fileSources.get(0);
        String sortUrl = fileSource.getUrl();
        if (StringUtils.isEmpty(sortUrl)) {
            sourceName = "base/common/";
        }

        List<Picture> list = new ArrayList<>();
        // 文件上传
        if (!CollectionUtils.isEmpty(filedatas)) {
            for (MultipartFile filedata : filedatas) {
                String oldName = filedata.getOriginalFilename();
                long size = filedata.getSize();
                String picExpandedName = FileUtils.getPicExpandedName(oldName); // 获取扩展名
                String newFileName = System.currentTimeMillis() + BaseConstant.SYMBOL_POINT + picExpandedName; // 获取新文件名
                String localuUrl = "";
                String qiNiuUrl = "";
                String minioUrl = "";
                try {
                    if (BlogOpenStatus.OPEN.equals(uploadQiNiu)) {
                        qiNiuUrl = qiniuService.uploadFile(filedata, newFileName);
                    }

                    if (BlogOpenStatus.OPEN.equals(uploadMinio)) {
                        minioUrl = minioService.uploadFile(filedata, newFileName);
                    }

                    if (BlogOpenStatus.OPEN.equals(uploadLocal)) {
                        localuUrl = localFileService.uploadFile(filedata, fileSource, newFileName);
                    }
                } catch (Exception e) {
                    log.info("上传文件异常:{}", e.getMessage());
                    e.getStackTrace();
                    return Wrapper.failed("文件上传失败，请检查系统配置");
                }

                Picture picture = new Picture();
                picture.setPicName(newFileName);
                picture.setFileSourceUid(fileSource.getUid());
                picture.setPicSize((double)size);
                picture.setPicExpendName(picExpandedName);
                picture.setLocalUrl(localuUrl);
                picture.setQiniuUrl(qiNiuUrl);
                picture.setMinioUrl(minioUrl);
                picture.setUserUid(userUid);
                picture.setAdminUid(adminUid);
                picture.setPicOldName(oldName);
                picture.setStatus(BlogStatus.ENABLE.getStatus());
                pictureMapper.insert(picture);
                list.add(picture);
            }
            return Wrapper.success(list);
        }
        return Wrapper.failed("请上传图片");
    }
}
